package com.shiguiwu.springmybatis.spring.scope;

import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.Scope;

import java.util.HashMap;
import java.util.Map;

/**
 * @description: 自定义bean的作用域。。。。。。线程级的bean
 * @author: stone
 * @date: Created by 2021/3/9 10:26
 * @version: 1.0.0
 * @pakeage: com.shiguiwu.springmybatis.spring.scope
 */
public class ThreadScope  implements Scope {

    public static final String THREAD_SCOPE = "thread";

    private ThreadLocal<Map<String, Object>> beanMap = new ThreadLocal<Map<String, Object>>(){
        @Override
        protected Map<String, Object> initialValue() {
            return new HashMap<String, Object>();
        }

    };
    @Override
    public Object get(String name, ObjectFactory<?> objectFactory) {
        return beanMap.get().computeIfAbsent(name, n -> objectFactory.getObject());
    }

    @Override
    public Object remove(String name) {
        System.out.println("移除对象：" + name);
        return beanMap.get().remove(name);
    }

    @Override
    public void registerDestructionCallback(String name, Runnable callback) {
        System.out.println("清理对象：" + name);
    }

    @Override
    public Object resolveContextualObject(String key) {
        return null;
    }

    @Override
    public String getConversationId() {
        return Thread.currentThread().getName();
    }
}
